package ru.chaykin;

import java.io.IOException;

import ru.chaykin.additionalinfo.AdditionalInfoActivity;
import ru.chaykin.exceptions.InvalidFileFormatException;
import ru.chaykin.load.ILoadDataProgress;
import ru.chaykin.load.IThreadException;
import ru.chaykin.load.LoadDataThread;
import ru.chaykin.menuenum.MapMenuEnum;
import ru.chaykin.rendering.OpenGLSceneRenderer;
import ru.chaykin.threadmanager.ThreadManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
import ru.chaykin.R;

/**
 * Активность просто отображает вид OpenGLSceneView
 */
public class RunOpenGLViewActivity extends Activity implements IThreadException {
	private ThreadManager tm;
	static boolean taskRuned = false;
	public int test;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		 
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);	//Убрать title bar
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setResult(RESULT_CANCELED, getIntent());
		
		setContentView(R.layout.open_gl_layout);
		
		tm = new ThreadManager();
		tm.handleRetainedTask(getLastNonConfigurationInstance());
		
		Button cancelButton = (Button)findViewById(R.id.cancelButton);
		cancelButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				OpenGLSceneView oglsv = (OpenGLSceneView)findViewById(R.id.OpenGLView);
				oglsv.cancelMeasurement();
			}
		});
		
		Button infoButton = (Button)findViewById(R.id.infoButton);
		infoButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				if (OpenGLSceneView.getSelectedObjectId() != OpenGLSceneRenderer.OBJECT_NOT_SELECTED) {
					Intent intent = new Intent();
	                intent.setClass(RunOpenGLViewActivity.this, AdditionalInfoActivity.class);
	                startActivity(intent);
				}
				else {
					//TODO строку в ресурсы
					Toast.makeText(getApplicationContext(), "Объект не выделен", Toast.LENGTH_LONG).show();
				}		
			}
		});
		
		if (!taskRuned) {
			tm.setThread(new LoadDataThread(this, (ILoadDataProgress)findViewById(R.id.OpenGLView), getIntent().getExtras().getString(OpenGLSceneView.PATH)));
			taskRuned = true;;
		}
		else {
			((LoadDataThread)tm.getThread()).setILoadDataProgress(this, (ILoadDataProgress)findViewById(R.id.OpenGLView));
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.map_menu, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		OpenGLSceneView openGLSceneView = (OpenGLSceneView) findViewById(R.id.OpenGLView);
		switch (item.getItemId()) {
		case R.id.subMenuGoniometry:
			openGLSceneView.mapMenuSelected(MapMenuEnum.SUB_GONIOMETRY);
			break;
		case R.id.subMenuArea:
			openGLSceneView.mapMenuSelected(MapMenuEnum.SUB_AREA);
			break;
		case R.id.subMenuRanging:
			openGLSceneView.mapMenuSelected(MapMenuEnum.SUB_RANGING);
			break;
		case R.id.menuInfo:
			openGLSceneView.mapMenuSelected(MapMenuEnum.ADDITIONAL_INFO);
			break;
		}
		return true;
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			new AlertDialog.Builder(this).setIcon(R.drawable.icon)
			.setTitle(getText(R.string.cancel_loading_msg))
			.setPositiveButton(getText(R.string.yes_msg), new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {
					Log.d(getClass().getName(), "Request to stop threads");
					((LoadDataThread)tm.getThread()).stopThread();	//Остановим потоки (там вложенный еще остановится)
					finish(); }
			}).setNegativeButton(getText(R.string.no_msg), new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {}
			}).show();
			return true;
		}
		return false;
	}
	
	@Override
    public Object onRetainNonConfigurationInstance() {
		return tm.retainTask();
    }

	public void onException(Exception e) {
		CharSequence exceptionMsg; 
		if (e instanceof InvalidFileFormatException)
			exceptionMsg = getText(R.string.invalid_file_format);
		else if (e instanceof IOException)
			exceptionMsg = getText(R.string.io_error);
		else
			exceptionMsg = getText(R.string.unknown_error);
		Toast.makeText(getApplicationContext(), exceptionMsg, Toast.LENGTH_LONG).show();
		setContentView(R.layout.main);
		finish();
	}
}

